package jehc.cloud.oauth.web;

import cn.hutool.core.collection.CollectionUtil;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import jehc.cloud.common.annotation.Auth;
import jehc.cloud.common.annotation.NeedLoginUnAuth;
import jehc.cloud.common.base.*;
import jehc.cloud.common.session.HttpSessionUtils;
import jehc.cloud.common.util.JsonUtil;
import jehc.cloud.common.util.StringUtil;
import jehc.cloud.oauth.constant.Constant;
import jehc.cloud.oauth.publisher.ChannelUtil;
import jehc.cloud.oauth.publisher.NettyUtil;
import jehc.cloud.oauth.util.OauthUtil;
import jehc.cloud.oauth.vo.ChannelEntity;
import jehc.cloud.oauth.vo.Transfer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
 * @Desc 授权中心在线用户API
 * @Author 邓纯杰
 * @CreateTime 2012-12-12 12:12:12
 */
@RestController
@RequestMapping("/oauthOnline")
@Api(value = "授权中心在线用户API",tags = "授权中心在线用户API",description = "授权中心在线用户API")
@Slf4j
public class OauthOnlineController extends BaseAction {

    @Autowired
    NettyUtil nettyUtil;
    @Autowired
    ChannelUtil channelUtil;

    @Autowired
    private HttpSessionUtils httpSessionUtils;
    @Autowired
    OauthUtil oauthUtil;

    /**
     * 查询在线账户列表
     */
    @NeedLoginUnAuth
    @PostMapping(value="/list")
    @ApiOperation(value="查询在线账户列表", notes="查询在线账户列表")
    public BasePage getOauthKeyInfoListByCondition(@RequestBody BaseSearch baseSearch){
        List<String> list  = httpSessionUtils.getAllTokenKey();
        List<BaseHttpSessionEntity> entityList = new ArrayList();
        String oauthAccountEntity ="";
        BaseHttpSessionEntity baseHttpSessionEntity ;
        for (String token : list ){
              oauthAccountEntity = httpSessionUtils.getAttribute(token);
              baseHttpSessionEntity  = JsonUtil.fromAliFastJson(oauthAccountEntity, BaseHttpSessionEntity.class);
              entityList.add(baseHttpSessionEntity);
        }
        commonHPager(baseSearch);
        PageInfo<BaseHttpSessionEntity> page = new PageInfo<BaseHttpSessionEntity>(entityList);
        return outPageBootStr(page,baseSearch);
    }


    /**
     * 剔除
     * @param account_id
     */
    @ApiOperation(value="剔除", notes="剔除")
    @DeleteMapping(value="/delete/{account_id}")
    @Auth("/oauthAccount/delete")
    public BaseResult delete(@PathVariable("account_id")String account_id){
        int i = 0;
        if(!StringUtil.isEmpty(account_id)){
            String token = oauthUtil.getTokenByAccountId(account_id);
            if(!StringUtil.isEmpty(token)){
                boolean res = oauthUtil.deleteToken(token);
                if(res){
                    i = 1;
                    publish(token);
                }
            }
        }
        if(i>0){
            return outAudStr(true);
        }else{
            return outAudStr(false);
        }
    }

    /**
     *
     * @param token
     */
    public void publish(String token){
        try {
            Map<String,ChannelEntity> map = channelUtil.getChannelConcurrentHashMap();
            if(CollectionUtil.isEmpty(map)){
                return;
            }
            Iterator<Map.Entry<String, ChannelEntity>> entries = map.entrySet().iterator();
            while (entries.hasNext()) {
                Map.Entry<String, ChannelEntity> entry = entries.next();
                ChannelEntity channelEntity = entry.getValue();
                channelEntity.getRequestInfo().setData(new Transfer(token, Constant.TOKEN_DESTORY));
                boolean res = nettyUtil.sendMessage(entry.getValue());
                log.info("发布Token至客户端. 发送结果：{}-Token：{}",res,token);
            }
        }catch (Exception e){
            log.info("发布Token至客户端异常. Token：{}-ERROR：{}",token,e);
        }
    }
}
